var express = require('express');
var router = express.Router();
const fs = require('fs')
const path = require('path')
const execSync = require('child_process').execSync
const root = path.join(__dirname, '../version')
const initVersion = '1.0.0.0'

/* GET home page. */
router.get('/start', function(req, res, next) {
  const name = req.query.name
  const changeUrl = path.join(root, name)
  const originPath = path.join(__dirname, '../../', name)
  const originDist = path.join(originPath, '/dist')

  let version
  let newVersion
  // 处理版本号
  function changeVersion () {
    try{
      version = fs.readFileSync(changeUrl).toString()
      version = +(version.replace(/\./g, '')) + 1
      newVersion = `${version}`.split('').join('.')
      fs.writeFileSync(changeUrl, newVersion)
    } catch (e) {
      fs.writeFileSync(changeUrl, initVersion)
      changeVersion()
    }
  }
  // 发布打包
  function startBuild() {
    const bagPath = path.join(__dirname, '../bag')

    // 清空当前项目下所有资源
    execSync(`rm -rf ${bagPath}/${name}`)

    // 首先创建项目目录
    execSync(`mkdir ${bagPath}/${name}`)

    try{
      // 进入项目并执行打包
      execSync(`cd ${originPath} && npm run build`)
    } catch (e) {}

    // 重新创建新的资源包
    execSync(`cd ${bagPath} && mkdir -p ./${name}/${newVersion}`)

    const lastDist = path.join(bagPath, `./${name}/${newVersion}`)

    try {
      execSync(`mv ${originDist} ${lastDist}`)

    } catch (e) {}
  }

  changeVersion()
  startBuild()

  res.send({
    version: newVersion,
  })
});


const versionDir = path.join(__dirname, '../version')
router.get('/', function(req, res, next) {
  const name = req.query.name
  console.log('name==', name, versionDir)
  /**
   * 确认更新版本，每个应用独立一个文件夹管理版本*
   */
  
  // 创建一个文件，默认版本号： initVersion

  const currentURL= path.join(versionDir, name)
  let newVersion = ''
  try {
    const originVersion = fs.readFileSync(currentURL).toString().replace(/\n/g, '')
    console.log('originVersion==', originVersion)
    // 修改版本号： 1.0.0.0 =》 1.0.0.1 右侧子版本号开始累加
    // 扩展： 学习replace正则用法，尤其是第二个参数都可以有哪些内容
    newVersion = originVersion.replace(/\.(\d+)$/,(a,b) => {
      console.log('a,b==', a,b)
      // +b把字符串类型转成数字型 '6' => 6
      return `.${+b + 1}`
    })
    console.log('newVersion==', newVersion)
    // 写入到文件中
    fs.writeFileSync(currentURL, newVersion)
  }catch(e){
    fs.writeFileSync(currentURL, initVersion)
  }

  /**构建打包发布*/ 

  // 获取需要打包的项目目录  
  const originPath = path.join(__dirname, '../../', name)
  // 打包后输出目录 
  const originDist = path.join(originPath,  'dist')
  // console.log('originDist==', originDist)
  // 保存打包后的文件
  const bagPath = path.join(__dirname,  '../bag')
  console.log('bagPath==', bagPath)
  try {
    execSync(`cd ${originPath} && npm i && npm run build`)
    
    // bagPah目录下生成对应项目目录
    // execSync(`cd ${bagPath} && mkdir -p ./${name}/${newVersion}`)

    // 执行上面命令报错，
    if(!fs.existsSync(`${bagPath}/${name}`)) {
      fs.mkdirSync(`${bagPath}/${name}`)
    }
    fs.mkdirSync(`${bagPath}/${name}/${newVersion}`)

    // 打包后的文件拷贝到bag/name下
    const lastDist = path.join(bagPath, `./${name}/${newVersion}`)
    // console.log('lastDist==', lastDist)
    try {
      execSync(`mv ${originDist} ${lastDist}`)
    }catch(e){
      console.log('move----',e)
    }
    
  }catch(e){
    console.log('err=========================', e)
  }
  
  res.send({
    msg: `build ${name} success`,
    version: newVersion
  })
});

module.exports = router;
